import {
  markerInfo,
  ANIMATION_DURATION,
  MAX_TRAIL_POINTS,
  CAMERA_UPDATE_INTERVAL,
  lerp,
  calculateBearing,
  simplifyTrail,
  getIds,
  setIds,
  getIsTrackingEnabled,
  setIsTrackingEnabled,
  getTrackingId,
  setTrackingId,
  getLastCameraUpdateTime,
  setLastCameraUpdateTime,
  realTimeLayer,
  updateTrailAndSegmentByPoints,
  updateTrailDisplay
} from "./realtimeTrackUtil";
import { createPopup, updatePopup, updatePopupPositition, closePopup } from "../popup/index";
import { LayerConfig, addLayer, LayerType, removeLayer, moveLayerAbove } from "../layer/layerManage.ts";
import { getLayerManagerState } from "../layer/layerManagerState.ts";
// 过滤添加还是修改位置
export const filterAddOrModify = (map: any, data: any) => {
  const { id, positions, info } = data;
  const currentIds = getIds();

  if (currentIds.includes(id)) {
    // 如果 ID 存在，则修改位置
    const previousPositions = markerInfo[id].positions;
    moveMarker(map, id, previousPositions, positions, ANIMATION_DURATION, info);
    markerInfo[id].positions = positions; // 更新上一帧位置
  } else {
    // 如果 ID 不存在，则添加标记
    currentIds.push(id);
    setIds(currentIds);
    addMarker(map, data, info);
    markerInfo[id] = { positions, trail: [], trailEnabled: false, popup: null, segments: [] }; // 存储标记信息和航迹线
  }
};

// 添加标记
export const addMarker = (map: any, data: any, info: any) => {
  const { id, positions } = data;

  // 添加标记的 GeoJSON 数据源
  const source = {
    type: "geojson",
    data: {
      type: "FeatureCollection",
      features: [
        {
          type: "Feature",
          geometry: {
            type: "Point",
            coordinates: positions
          },
          properties: { ...info }
        }
      ]
    }
  };
  const layer: LayerConfig = {
    id: `marker-${id}`,
    type: LayerType.Symbol,
    source: source,
    layout: {
      "icon-image": "airport-15", // 使用 Mapbox 自带的图标
      "icon-rotate": 0,
      "icon-rotation-alignment": "map",
      "icon-allow-overlap": true,
      "icon-ignore-placement": true,
      "icon-size": 1
    }
  };
  // 添加标记的 symbol 图层
  // map.addLayer();
  addLayer(getLayerManagerState(map), layer);
};

// 移动标记
export const moveMarker = (
  map: mapboxgl.Map,
  id: string,
  start: [number, number],
  end: [number, number],
  duration: number,
  info: any
) => {
  let startTime: number | null = null;

  const animate = (timestamp: number) => {
    const currentIds = getIds();
    if (!currentIds.includes(id)) {
      return;
    }
    if (!startTime) startTime = timestamp;
    const progress = timestamp - startTime;
    const fraction = Math.min(progress / duration, 1);

    const currentPosition = lerp(start, end, fraction);

    // 更新标记的位置
    const markerSource = map.getSource(`marker-${id}`) as mapboxgl.GeoJSONSource;
    if (markerSource) {
      markerSource.setData({
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: currentPosition
            },
            properties: { ...info }
          }
        ]
      });
    }

    // 更新标记的朝向
    const bearing = calculateBearing(start, end);
    map.setLayoutProperty(`marker-${id}`, "icon-rotate", bearing);

    // 更新航迹线
    if (markerInfo[id].trailEnabled) {

      // const currentPosition = [currentPosition[0], currentPosition[1]];
      updateTrailAndSegmentByPoints(id, currentPosition);
      updateTrailDisplay(map, id); // 确保此函数已定义，用于更新地图显示
      // const trail = markerInfo[id].trail;
      // trail.push(currentPosition);
      // if (trail.length > MAX_TRAIL_POINTS) {
      //   trail.shift();
      // }
      // // console.log(trail);
      // // 简化航迹线（保留关键点）
      // const simplifiedTrail = simplifyTrail(trail);
      // const trailSource = map.getSource(`trail-${id}`) as mapboxgl.GeoJSONSource;
      // if (trailSource) {
      //   trailSource.setData({
      //     type: "FeatureCollection",
      //     features: [
      //       {
      //         type: "Feature",
      //         geometry: {
      //           type: "LineString",
      //           coordinates: simplifiedTrail
      //         },
      //         properties: {}
      //       }
      //     ]
      //   });
      // }
    }

    // 更新 Popup 的位置和内容
    if (markerInfo[id].popup) {
      info.coordinates = [currentPosition[0], currentPosition[1]];
      updatePopupPositition(`popup-${id}`, currentPosition);
      updatePopup(markerInfo[id].popup, realTimeLayer(info));
    }

    // 更新相机位置（如果启用了追踪）
    if (getIsTrackingEnabled() && getTrackingId() === id) {
      const now = Date.now();
      if (now - getLastCameraUpdateTime() >= CAMERA_UPDATE_INTERVAL) {
        map.flyTo({
          center: currentPosition,
          speed: 0.5, // 控制相机移动速度
          curve: 1, // 平滑移动
          essential: true // 确保动画不会被中断
        });
        setLastCameraUpdateTime(now);
      }
    }

    if (fraction < 1) {
      requestAnimationFrame(animate);
    }
  };

  requestAnimationFrame(animate);
};

// 移除标记和航迹线
export const removeMarker = (map: mapboxgl.Map, id: string) => {
  const currentIds = getIds();
  if (currentIds.includes(id)) {
    // 清除航迹分段
    clearTrailSegments(map, id);

    // 移除标记图层
    removeLayer(getLayerManagerState(map), `marker-${id}`);
    removeLayer(getLayerManagerState(map), `trail-${id}`);

    // 移除 Popup
    if (markerInfo[id].popup) {
      markerInfo[id].popup.remove();
    }

    // 更新 ID 列表
    const newIds = currentIds.filter(existingId => existingId !== id);
    setIds(newIds);
    delete markerInfo[id];
  }
};

/**
 * 删除指定飞机的所有航迹分段
 * @param map - Mapbox 地图实例
 * @param id - 飞机 ID
 */
export const clearTrailSegments = (map: mapboxgl.Map, id: string) => {
  const marker = markerInfo[id];
  if (!marker) return;

  // 清空分段数据
  marker.segments = [];

  // 清空原始航迹点
  marker.trail = [];

  // 更新航迹线显示（清空地图上的航迹线）
  updateTrailDisplay(map, id);
};

// 动态加载或移除航迹线
export const toggleTrailVisibility = (map: mapboxgl.Map, id: any, isVisible: boolean, color: string = "#FF0000", width: number = 2) => {
  const currentIds = getIds();
  if (currentIds.includes(id)) {
    if (isVisible) {
      // 如果航迹线未加载，则加载航迹线
      const source = {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: []
        }
      };
      const layer: LayerConfig = {
        id: `trail-${id}`,
        type: LayerType.Line,
        source: source,
        paint: {
          "line-color": color, // 使用传入的颜色参数
          "line-width": width  // 使用传入的宽度参数
        }
      };
      // 添加航迹线的 line 图层，并插入到飞机图层下方

      addLayer(getLayerManagerState(map), layer);

      // 标记航迹线为启用状态
      markerInfo[id].trailEnabled = true;

      // 将 Popup 存储在 markerInfo 中
      markerInfo[id].popup = createPopup(map, `popup-${id}`, getMarkerPosition(id), realTimeLayer({}));

      // 相机追踪
      // toggleCameraTracking(map, id);
    } else {
      // 如果航迹线已加载，则移除航迹线
      removeLayer(getLayerManagerState(map), `trail-${id}`);

      // 标记航迹线为禁用状态
      markerInfo[id].trailEnabled = false;

      // 禁用 Popup
      closePopup(`popup-${id}`);
    }

    // 初始化分段数据
    if (marker.segments.length === 0) {
      marker.segments.push({
        id: `${id}-segment-1`,
        points: [marker.positions],
        pointCount: 1
      });
    }

    // 添加航迹线图层
    if (!map.getLayer(`trail-${id}`)) {
      map.addLayer({
        id: `trail-${id}`,
        type: "line",
        source: `trail-${id}`,
        paint: {
          "line-color": "#FF0000",
          "line-width": 2,
          "line-opacity": 0.8
        }
      });
    }
    // 标记航迹线为启用状态
    markerInfo[id].trailEnabled = true;

    // 将 Popup 存储在 markerInfo 中
    markerInfo[id].popup = createPopup(map, `popup-${id}`, getMarkerPosition(id), realTimeLayer({}));
    // 更新显示
    updateTrailDisplay(map, id);
  } else {
    // 移除航迹线
    if (map.getLayer(`trail-${id}`)) map.removeLayer(`trail-${id}`);
    if (map.getSource(`trail-${id}`)) map.removeSource(`trail-${id}`);
    // 标记航迹线为禁用状态
    markerInfo[id].trailEnabled = false;

    // 禁用 Popup
    closePopup(`popup-${id}`);
  }

  marker.trailEnabled = isVisible;
};

// 获取当前飞机的坐标信息
export const getMarkerPosition = (id: any): [number, number] | null => {
  const currentIds = getIds();
  if (currentIds.includes(id) && markerInfo[id]) {
    return markerInfo[id].positions; // 返回当前坐标
  }
  return null; // 如果 ID 不存在，返回 null
};

// 启用或禁用相机追踪
export const toggleCameraTracking = (map: mapboxgl.Map, id: string | null) => {
  setIsTrackingEnabled(!!id); // 启用或禁用追踪
  setTrackingId(id); // 设置当前追踪的标记 ID
};

// 修改航迹线样式
export const updateTrailStyle = (map: mapboxgl.Map, id: string, color?: string, width?: number) => {
  const trailLayerId = `trail-${id}`;
  if (map.getLayer(trailLayerId)) {
    if (color) {
      map.setPaintProperty(trailLayerId, "line-color", color);
    }
    if (width) {
      map.setPaintProperty(trailLayerId, "line-width", width);
    }
  }
};
